/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);

var E = window.wangEditor;
var editor = new E('#editor');

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['article:add', 'article:update'],//本页权限数组
        selects: [],
        actSelects: [],
        content: '',
        schoolId: schoolId,
        schoolList: schoolMap,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        that.getTypeList();
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);

            return;
        }
        if (!empty(aGET.id)) {
            that.getInfoById(aGET.id);
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        getTypeList: function () {
            var that = this;
            Get(that, _HOST + _API.actArt_articleType_getArticleType + "?companyId=" + companyId + "&schoolId=" + schoolId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        that.selects = response;
                    }
                });
        },
        // 选择进入不同页面选择
        selectOp: function() {
            var type = $("#type").val();
            var url = "../pages/goods.html";
            var index = layer.open({
                type: 2,
                title: "选择对象",
                content: url,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
                end:function(){//关闭后调用的事件
                    var objectId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.selectOp.objectId);
                    var objectName = sessionStorageUtils.getJson(storageKey.sessionStorageKey.selectOp.objectName);
                    $("#Form input[name='objectId']").val(objectId);
                    $("#Form input[name='objectName']").val(objectName);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.selectOp.objectId);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.selectOp.objectName);
                }
            });
            layer.full(index);
        },
        changeType: function() {
            $("#Form input[name='objectId']").val('');
            $("#Form input[name='objectName']").val('');
        },
        getInfoById: function (id) {
            var that = this;
            Get(that, _HOST + _API.actArt_article_getById + "?id=" + id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            var list = response.data;
                            var oldImgId = "";
                            for (var item in list) {
                                if (item == 'imgId') {
                                    oldImgId = list[item];
                                }
                                if (item == 'content') {
                                    editor.txt.html(list[item]);
                                }
                                if (item == 'showUrl') {
                                    initFileUpload(list[item]);
                                }
                                if (item == 'type') {
                                    $("#Form select[name='type']").val(list[item]);
                                }
                                if (item == 'articleType') {
                                    $("#Form select[name='articleType']").val(list[item]);
                                }
                                if (item == 'objectId') {
                                    $("#Form select[name='objectId']").val(list[item]);
                                }
                                if (item == 'isTop') {
                                    $("#Form select[name='isTop']").val(list[item]);
                                }
                                if (item == 'schoolId') {
                                    $("#Form select[name='schoolId']").val(list[item]);
                                }
                                $("#Form input[name='" + item + "']").val(list[item]);
                            }
                            $("#Form input[name='oldImgId']").val(oldImgId);
                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        // 得到微信文章
        getWxArticle: function () {
            var that = this;
            let url = $("#contentUrl").val();
            if (url == null || url == '') {
                layer.msg("链接为空。", {time: 1500, icon: 5});
                return;
            }
            Post(that, _HOST + _API.actArt_article_getWxArticle, {url: url}, true, '')
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            var result = response.data;
                            $("#title").val(result.title);
                            $("#digest").val(result.desc);
                            editor.txt.html(result.content);
                            initFileUpload(result.imgUrl);
                            $("#articleImg").val(result.imgId);
                            $(".file-caption-name").text(result.imgId);
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        // 添加
        add: function () {
            var that = this;
            $("#articleContent").val(editor.txt.html());
            var param = {};
            $("#Form").find('input,textarea,select').each(function () {
                param[$(this).attr('name')] = $(this).val();
            });
            param['companyId'] = companyId;
            //console.log(param)
            Post(that, _HOST + _API.actArt_article_add, param, true, that.permissions[0])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 修改
        update: function () {
            var that = this;
            $("#articleContent").val(editor.txt.html());
            var param = {};
            $("#Form").find('input,textarea,select').each(function () {
                param[$(this).attr('name')] = $(this).val();
            });
            param['companyId'] = companyId;
            // console.log(param)
            Post(that, _HOST + _API.actArt_article_update, param, true, that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
    },
});


function initFileUpload(url) {
    $("#fileUploadBtn").fileinput('destroy');
    $("#fileUploadBtn").fileinput({
        language: "zh",
        uploadUrl: _HOST + _API.common_file_ossUpload,
        ajaxSettings: {
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传预览图片",
        browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
        allowedFileExtensions: ['jpg', 'gif', 'png'],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                size: 329892,
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            $(".file-caption-name").text(data.response.attachemId);
            $("#articleImg").val(data.response.attachemId);
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

$(function () {
    editor.customConfig.uploadImgServer = _HOST + _API.common_file_ossWe;
    editor.customConfig.uploadFileName = 'file';
    editor.customConfig.uploadImgHeaders = {
        'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
        'permCoding': '',
        'enctype': 'multipart/form-data'
    };
    editor.customConfig.zIndex = 100;
    editor.create();
    if (empty(aGET.id)) {
        initFileUpload('');
    }
});

$('#Form').data('bootstrapValidator', null);
Validator();

function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            title: {
                validators: {
                    notEmpty: {
                        message: '标题不能为空'
                    },
                    stringLength: {
                        max: 50,
                        message: '标题长度最多50个字符（一个汉字占两个字符）'
                    },
                }
            },
            digest: {
                validators: {
                    notEmpty: {
                        message: '摘要不能为空'
                    },
                    stringLength: {
                        max: 200,
                        message: '摘要长度最多200个字符（一个汉字占两个字符）'
                    },
                }
            },
            sort: {
                validators: {
                    notEmpty: {
                        message: '排序不能为空'
                    },
                }
            },
            type: {
                validators: {
                    notEmpty: {
                        message: '请选择类型'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if (empty(aGET.id)) {
            app.add();
        } else {
            app.update();
        }
    });
}
